package com.huang.CAS;


import lombok.NoArgsConstructor;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

@NoArgsConstructor
class lock{
  private  AtomicReference<Thread> reference=  new AtomicReference();

  public void mylock(){
      while (!reference.compareAndSet(null,Thread.currentThread())){

      }
      System.out.println("上锁成功。。。。");
  }

    public void myunlock(){
        while (!reference.compareAndSet(Thread.currentThread(),null)){

        }
        System.out.println("释放锁成功。。。。");
    }




}

public class casLock {
    public static void main(String[] args) {
        lock lock = new lock();

        for (int i = 0; i < 2; i++) {
            new Thread(()->{
                lock.mylock();
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                lock.myunlock();
            }).start();
        }


    }
}
